package com.like.fragment;

import android.content.Context;
import android.view.View;
import android.widget.ListView;

import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.like.adapter.DocumentAdapter;
import com.like.entity.Department;
import com.like.entity.DownloadCourseReq;
import com.like.entity.EventWrapper;
import com.like.entity.GeneralResponse;
import com.like.entity.InfoListReq;
import com.like.entity.InfoListResp;
import com.like.hospitalworld.MainActivity;
import com.like.hospitalworld.R;
import com.like.likeutils.network.RetrofitCallback;
import com.like.network.InfoService;
import com.like.network.ResponseCode;
import com.like.network.RetrofitUtil;
import com.like.utils.Constants;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import java.util.List;

import retrofit2.Call;
import retrofit2.Response;

@ContentView(R.layout.fragment_main_document)
public class MainDocumentFragment extends BaseFragment {

    public static final int REQUEST_COURSE_DOWNLOAD = 100;

    @ViewInject(R.id.document_list)
    PullToRefreshListView mDocumentList;

    private DocumentAdapter mDocAdapter;
    private MainActivity mMainActivity;
    private InfoService mInfoService;
    private Department mCurrentDep;
    private int mType;
    private int mCurrentPage = 0;
    private int mPageCount = 15;

    @Override
    protected void onCreateView() {
        super.onCreateView();
        EventBus.getDefault().register(this);
        setToolbar();
        initList();
        mCurrentDep = m.getCurrentDep();
        mInfoService = RetrofitUtil.getService(InfoService.class);
        getInfoList(false);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Subscribe
    public void getEvent(EventWrapper event) {
        if (EventWrapper.isMatch(event, getClass(), REQUEST_COURSE_DOWNLOAD)) {
            InfoListResp.InformationBase info = (InfoListResp.InformationBase) event.data;
            DownloadCourseReq req = new DownloadCourseReq(info.id, m.getLoginResp().userID);
            Call<Object> call = mInfoService.downloadCourse(Constants.getGUID(), m.getToken(), req);
            call.enqueue(new RetrofitCallback<Object>() {
            });
        }
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (getActivity() instanceof MainActivity)
            mMainActivity = (MainActivity) getActivity();
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        if (!hidden) {
            setToolbar();
            Department currentDep = m.getCurrentDep();
            if (currentDep != null && mCurrentDep != null) {
                if (currentDep.id != mCurrentDep.id) {
                    mCurrentPage = 0;
                    mCurrentDep = m.getCurrentDep();
                    getInfoList(false);
                }
            }
        }
    }

    private void setToolbar() {
        View v = mMainActivity.setToolbar(R.layout.toolbar_doc);
        x.view().inject(this, v);
    }

    private void initList() {
        mDocumentList.setMode(PullToRefreshBase.Mode.BOTH);
        mDocumentList.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
                mCurrentPage = 0;
                getInfoList(false);
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
                mCurrentPage += 1;
                getInfoList(true);
            }
        });
    }

    private void getInfoList(final boolean append) {
        InfoListReq req = new InfoListReq(mCurrentDep.subDeps.get(3).id, mCurrentPage, mPageCount);
        Call<GeneralResponse<InfoListResp>> call = mInfoService.getInfoList(Constants.getGUID(),
                m.getToken(), req);
        call.enqueue(new RetrofitCallback<GeneralResponse<InfoListResp>>() {
            @Override
            public void onResponse(Call<GeneralResponse<InfoListResp>> call,
                                   Response<GeneralResponse<InfoListResp>> response) {
                mDocumentList.onRefreshComplete();
                if (!response.isSuccessful())
                    return;
                GeneralResponse res = response.body();
                if (res.result != ResponseCode.SUCCESS)
                    return;
                List<InfoListResp.InformationBase> infos = response.body().data.informationBaseList;
                if (mDocAdapter == null) {
                    mDocAdapter = new DocumentAdapter(infos, m);
                    mDocumentList.setAdapter(mDocAdapter);
                } else {
                    mDocAdapter.update(infos, append);
                }
            }

            @Override
            public void onFailure(Call<GeneralResponse<InfoListResp>> call, Throwable t) {
                t.printStackTrace();
                mDocumentList.onRefreshComplete();
            }
        });
    }
}
